package com.snack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snack.common.result.Result;
import com.snack.entity.pojo.Store;
import com.snack.entity.pojo.User;
import com.snack.mapper.UserMapper;
import com.snack.service.StoreService;
import com.snack.service.UserService;
import com.snack.utils.PasswordUtil;
import com.snack.utils.UserIdThreadLocal;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author huangfuhao
 * @Date 2025/3/18
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public Result addManager(User manager) {
        log.info("为店铺新增店长");
        //查看用户名是否重复
        User user = lambdaQuery().eq(User::getUsername, manager.getUsername()).one();
        if (user != null) {
            return Result.error("用户名已存在");
        }

        //查询该店铺是否拥有店长
        User one = lambdaQuery().eq(User::getRoleId, 2l).eq(User::getStoreId, manager.getStoreId()).one();
        if (one != null) {
            return Result.error("该店铺已拥有店长，请先删除原店长");
        }
        //添加店长
        manager.setPassword(PasswordUtil.encodePassword(manager.getPassword()));//md5加密
        manager.setRoleId(2l);
        boolean save = save(manager);
        if (!save) {
            return Result.error("添加失败");
        }
        return Result.success(manager);
    }

    @Override
    public Result addEmployee(User user) {
        log.info("为店铺新增店员");

        //查看用户名是否重复
        User user1 = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
        if (user1 != null) {
            return Result.error("用户名已存在");
        }

        user.setPassword(PasswordUtil.encodePassword(user.getPassword()));//md5加密
        user.setRoleId(3l);
        boolean save = save(user);
        if (!save) {
            return Result.error("添加失败");
        }
        return Result.success(user);
    }

    @Override
    public Result listEmployee() {
        //获取登录用户id并查询信息
        Long userId = UserIdThreadLocal.getUserId();
        User user = getById(userId);
        Long storeId = user.getStoreId();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //获取roleId不等于4的用户
        wrapper.ne(User::getRoleId, 4);
        //管理员则可以获取所有用户信息
        if (user.getRoleId() != 1) {
            //如果不是管理员则仅可获取店铺拥有的员工列表
            log.info("查询该店铺下员工列表：{}", storeId);
            wrapper.eq(User::getStoreId, storeId);
        }
        //判断用户是否是管理员
        List<User> list = list(wrapper);

        return Result.success(list);
    }

    @Override
    public Result deleteEmployee(User user) {
        log.info("删除员工：{}", user);

        User user1 = getById(user.getId());
        boolean b = removeById(user);
        if (!b) {
            Result.error("删除失败");
        }
        return Result.success(user1);
    }

    @Override
    public Result updateUser(User user) {
        log.info("更新用户信息：{}", user);

        // 根据用户ID查询用户是否存在
        User existingUser = getById(user.getId());
        if (existingUser == null) {
            return Result.error("用户不存在");
        }

        // 如果用户名需要更新，检查新用户名是否已存在
        if (user.getUsername() != null && !user.getUsername().equals(existingUser.getUsername())) {
            User userWithSameName = lambdaQuery().eq(User::getUsername, user.getUsername()).one();
            if (userWithSameName != null) {
                return Result.error("用户名已存在");
            }
        }

        // 更新密码时进行加密
        if (user.getPassword() != null) {
            user.setPassword(PasswordUtil.encodePassword(user.getPassword()));
        }

        // 更新用户信息
        boolean update = updateById(user);
        if (!update) {
            return Result.error("更新失败");
        }
        return Result.success(user);
    }

}
